package cn.siat.gene.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.siat.common.core.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.siat.common.core.utils.StringUtils;
import cn.siat.common.core.web.controller.BaseController;
import cn.siat.common.core.web.domain.AjaxResult;
import cn.siat.common.core.web.page.TableDataInfo;
import cn.siat.common.log.annotation.Log;
import cn.siat.common.log.enums.BusinessType;
import cn.siat.common.security.annotation.RequiresPermissions;
import cn.siat.common.security.utils.SecurityUtils;
import cn.siat.gene.domain.ModelInfo;
import cn.siat.gene.domain.ProgrammeState;
import cn.siat.gene.service.IProgrammeStateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 方案状态表
 * @Author: Administrator
 * @Date: 2022-10-22
 * @Version: V1.0
 */
@Api(tags = "方案状态表")
@RestController
@RequestMapping("/programmestate")
@Slf4j
public class ProgrammeStateController extends BaseController {
    @Autowired
    private IProgrammeStateService programmeStateService;

    /**
     * 分页列表查询
     *
     * @param programmeState
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "方案状态表-分页列表查询", notes = "方案状态表-分页列表查询")
    @RequiresPermissions("system:programmestate:list")
    @GetMapping(value = "/list/page")
    public TableDataInfo queryPageList(ProgrammeState programmeState,
                                       @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        startPage();
        QueryWrapper<ProgrammeState> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ProgrammeState> wrapper = new QueryWrapper<>();
        Integer[] states = Convert.toIntArray(programmeState.getStates());
        if(StringUtils.isNotEmpty(programmeState.getProgrammeName())){
            queryWrapper.like("programme_name",programmeState.getProgrammeName().trim());
            wrapper.like("programme_name",programmeState.getProgrammeName().trim());
        }
        queryWrapper.eq("is_read", 0).eq("is_delete", 1);
        if(programmeState.getStartDate()!=null){
            queryWrapper.apply("to_date(cast(update_time as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " BETWEEN " +
                    "to_date(cast('"+programmeState.getStartDate()+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " AND " +
                    "to_date(cast('"+programmeState.getEndDate()+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')");
            wrapper.apply("to_date(cast(update_time as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " BETWEEN " +
                    "to_date(cast('"+programmeState.getStartDate()+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " AND " +
                    "to_date(cast('"+programmeState.getEndDate()+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')");
        }
        if(states != null && states.length >= 1){
            queryWrapper.in("programme_state", Arrays.asList(states));
            wrapper.in("programme_state", Arrays.asList(states));
        }
        queryWrapper.orderByDesc("update_time");
        List<ProgrammeState> list = programmeStateService.list(queryWrapper);
        List<ProgrammeState> defaultList = programmeStateService.list(wrapper.
                eq("is_read",1).eq("is_delete", 1).orderByDesc("update_time"));
        defaultList.addAll(list);
        return getDataTable(defaultList);
    }

    /**
     * 添加
     *
     * @param programmeState
     * @return
     */
    @Log(title = "方案状态表-添加", businessType = BusinessType.INSERT)
    @ApiOperation(value = "方案状态表-添加", notes = "方案状态表-添加")
    @RequiresPermissions("system:programmestate:list")
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody ProgrammeState programmeState) {
        programmeState.setIsDelete(1);
        programmeState.setIsRead(0);
        programmeState.setCreateTime(new Date());
        programmeState.setUpdateTime(new Date());
        programmeState.setCreateStaffNo(SecurityUtils.getUserId());
        programmeState.setUpdateStaffNo(SecurityUtils.getUserId());
        programmeStateService.save(programmeState);
        return toAjax(true);
    }

    /**
     * 编辑
     *
     * @param programmeState
     * @return
     */
    @Log(title = "方案状态表-编辑", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "方案状态表-编辑", notes = "方案状态表-编辑")
    @RequiresPermissions("system:programmestate:edit")
    @PutMapping(value = "/edit")
    public AjaxResult edit(@RequestBody ProgrammeState programmeState) {
        programmeState.setUpdateStaffNo(SecurityUtils.getUserId());
        programmeState.setUpdateTime(new Date());
        programmeStateService.updateById(programmeState);
        return toAjax(true);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "方案状态表-通过id删除", businessType = BusinessType.DELETE)
    @ApiOperation(value = "方案状态表-通过id删除", notes = "方案状态表-通过id删除")
    @RequiresPermissions("system:programmestate:remove")
    @DeleteMapping(value = "/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {
        isExist(id);
        programmeStateService.removeById(id);
        return toAjax(true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "方案状态表-批量删除", businessType = BusinessType.DELETE)
    @ApiOperation(value = "方案状态表-批量删除", notes = "方案状态表-批量删除")
    @RequiresPermissions("system:programmestate:remove")
    @DeleteMapping(value = "/deleteBatch/{ids}")
    public AjaxResult deleteBatch(@PathVariable String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            isExist(ids[i]);
            programmeStateService.removeById(ids[i]);
        }
        return toAjax(true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "方案状态表-通过id查询", notes = "方案状态表-通过id查询")
    @GetMapping(value = "/queryById")
    public AjaxResult queryById(@RequestParam(name = "id", required = true) String id) {
        ProgrammeState programmeState = programmeStateService.getById(id);
        if (programmeState == null) {
            return toAjax(false);
        }
        return AjaxResult.success(programmeState);
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @ApiOperation(value = "模型信息-查询全部数据", notes = "模型信息-查询全部数据")
    @GetMapping(value = "/list")
    public AjaxResult queryList() {
        QueryWrapper<ProgrammeState> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("programme_state", 1); // 查询有效地
        queryWrapper.eq("is_delete", 1); // 查询有效地
        queryWrapper.orderByAsc("create_time");
        return AjaxResult.success(programmeStateService.list(queryWrapper));
    }
    /**
     * 校验名称(已存在返回true)
     * @return
     */
    @GetMapping("/checkName")
    public AjaxResult checkName(String programmeName,String id){
        Boolean isExist = programmeStateService.checkName(programmeName,id);
        return AjaxResult.success(isExist);
    }
    /**
     * 校验编号(已存在返回true)
     * @return
     */
    @GetMapping("/checkNumber")
    public AjaxResult checkNumber(String programmeNumber,String id){
        Boolean isExist = programmeStateService.programmeNumber(programmeNumber,id);
        return AjaxResult.success(isExist);
    }

    @GetMapping("getSimpleList")
    public AjaxResult getSimpleList(){
        List<Map<String, String>> list = programmeStateService.getSimpleList();
        return AjaxResult.success(list);
    }

    private void isExist(String id){
        ProgrammeState programmeState = programmeStateService.getById(id);
        if(programmeState == null || 0 == programmeState.getIsDelete()){
            throw new ServiceException("删除方案状态不存在！");
        }
    }
}
